package servlet;

import Dao.JdbcTools;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import model.VueStu;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/vueinsert")
public class Vueinsert extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        System.out.println(123456);
        String data1 = req.getParameter("data");
        System.out.println("data1 = " + data1);
        //json格式转换json对象
        JSONObject jsonObject = JSONObject.parseObject(data1.toString());
        System.out.println("jsonObject = " + jsonObject);
        //获取对象中各个属性的值
        String id = jsonObject.getString("id");
        String name = jsonObject.getString("name");
        String age = jsonObject.getString("age");
        String height = jsonObject.getString("height");
        String school = jsonObject.getString("school");
        try {
            int i = JdbcTools.update1("insert into vue values(?,?,?,?,?)",id,name,age,height,school);
            System.out.println("i = " + i);
            String res = JSON.toJSONString(i);
            System.out.println("后端json格式的字符串1="+res);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //传回前端json格式的字符串key--value
        PrintWriter writer = resp.getWriter();
        writer.write("success");

    }
}
